#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "main.h"
#include "usart.h"
#include "app_debug.h"

#include "freertos.h"
#include "task.h"
#include "stream_buffer.h"
#include "queue.h"
#include "semphr.h"



#define DEBUG_UART huart1
#define DEBUG_BUFFER_SIZE 300

StreamBufferHandle_t streamDebug;
SemaphoreHandle_t semDebug;


void debug_uart_handler()
{
	uint8_t ch;
	BaseType_t xHigherPriorityTaskWoken = pdFALSE;
	if (__HAL_UART_GET_FLAG(&DEBUG_UART, UART_FLAG_TXE) != RESET)
	{
		__HAL_UART_CLEAR_FLAG(&DEBUG_UART, UART_FLAG_TXE);
		if(xStreamBufferReceiveFromISR(streamDebug,&ch,1,&xHigherPriorityTaskWoken))
		{
			DEBUG_UART.Instance->TDR=ch;
		}
		else
		{
			__HAL_UART_DISABLE_IT(&DEBUG_UART,UART_IT_TXE);
		}
		
	}		
}


void debug_printf(const char *fmt, ...)
{	
	va_list args; 
	if(xSemaphoreTake(semDebug,5)==pdFALSE)return;
	va_start(args,fmt); 
	vprintf(fmt,args); 
	va_end(args); 
	xSemaphoreGive(semDebug);	
}

void debug_init()
{
	streamDebug=xStreamBufferCreate(DEBUG_BUFFER_SIZE,1);
	semDebug=xSemaphoreCreateMutex();
}

int fputc(int ch,FILE *file)
{
	xStreamBufferSend(streamDebug,&ch,1,1000);
	__HAL_UART_ENABLE_IT(&DEBUG_UART,UART_IT_TXE);	
	return ch;
}


